﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioPlayer : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField]
    private AudioClip clip;
    [SerializeField]
    private AudioGroup group;
    [SerializeField]
    private bool playOnStart = false;
    private void Start()
    {
        if (playOnStart)
        {
            audioSource = GetComponent<AudioSource>();
            if (audioSource == null)
            {
                audioSource = gameObject.AddComponent<AudioSource>();
            }
            audioSource.volume = AudioManger.Instance.GetVolume(group);
            audioSource.PlayOneShot(clip);
        }
        //监听音量变化的事件,如果变化的组是自己的组,自己的音量也需要随之改变
        AudioManger.Instance.OnVolumeChange += ChangeVolume;
    }
    public void Play(AudioClip clip, AudioGroup group)
    {
        if (audioSource == null) audioSource = gameObject.AddComponent<AudioSource>();
        this.clip = clip;
        this.group = group;
        //根据group设置音量
        audioSource.volume = AudioManger.Instance.GetVolume(group);

        //根据名字判断应该使用的Mixer
        string name = clip.name;

        audioSource.PlayOneShot(clip);
    }

    private void ChangeVolume(AudioGroup group, float volume)
    {
        if (group == this.group)
        {
            audioSource.volume = volume;
        }
    }
}